package com.zhangjun.socket.handler;

import com.alibaba.fastjson.JSON;
import com.zhang.view.chat.IChatMethod;
import com.zhangjun.application.UIService;
import com.zhangjun.chat.protocol.login.LoginResponse;
import com.zhangjun.chat.protocol.login.dto.UserFriendDto;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import javafx.application.Platform;
import java.util.List;

/**
 * 虫洞栈：https://bugstack.cn
 * 公众号：bugstack虫洞栈  ｛关注获取学习源码｝
 * Create by 小傅哥 on 2019
 */
public class LoginHandler extends SimpleChannelInboundHandler<LoginResponse> {

    private UIService uiService;

    public LoginHandler(UIService uiService) {
        this.uiService = uiService;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginResponse msg) throws Exception {
        System.out.println("\r\n> msg handler ing ...");

        System.out.println("消息内容：" + JSON.toJSONString(msg));

        if (!msg.isSuccess()) {

            System.out.println("登陆失败");

            return;

        }

        Platform.runLater(() -> {

            uiService.getLogin().doLoginSuccess();

            IChatMethod chat = uiService.getChat();

            // 设置用户信息

            chat.setUserInfo(msg.getUserId(), msg.getUserNickName(), msg.getUserHead());


            // 好友
            List<UserFriendDto> userFriendList = msg.getUserFriendList();
            if (null != userFriendList) {
                userFriendList.forEach(friend -> chat.addFriendUser(false, friend.getFriendId(), friend.getFriendName(), friend.getFriendHead()));
            }

        });

    }

}
